// store/user.ts
import { defineStore } from 'pinia'
import { LocalStorage } from './local'

interface UserState {
	isLoggedIn: boolean
	username: string
	uuid: string
	signature: string
	avatar: string
	token: string
}

export const useUserStore = defineStore('user', {
	state: (): UserState => ({
		isLoggedIn: false,
		username: '',
		uuid: '',
		signature: '',
		avatar: '',
		token: '',
	}),
	actions: {
		getLoginIn() {
			return this.isLoggedIn
		},
		init() {
			this.isLoggedIn = false
			this.username = ''
			this.uuid = ''
			this.avatar = ''
			this.signature = ''
			this.token = ''
		},
		login(data: any) {
			this.isLoggedIn = true
			this.username = data.username
			this.uuid = data.uuid
			this.avatar = data.avatar
			LocalStorage.update(data)
		},
		logout() {
			this.init()
			LocalStorage.init()
		},
		setToken(token: string) {
			this.token = token
			localStorage.setItem('token', token)
		},
		getToken() {
			return localStorage.getItem('token')
		},
		setLoginStatus(status: string) {
			localStorage.setItem('saveLoginStatus', status)
		},
		loadFromLocalStorage() {
			const saveLoginStatus = localStorage.getItem('saveLoginStatus') //下次记得直接传结构体，不然key容易错
			if (saveLoginStatus === 'true') {
				this.username = localStorage.getItem('username') || ''
				this.uuid = localStorage.getItem('uuid') || ''
				this.avatar = localStorage.getItem('avatar') || ''
				this.isLoggedIn = true
			} else {
				this.logout()
			}
		},
		setChatUsername(username: string) {
			localStorage.setItem('chat', username)
		},
		getChatUsername() {
			return localStorage.getItem('chat')
		},
	},
})
